package com.op.teachingliteapp.fragment.seminar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.op.teachingliteapp.R;
import com.op.teachingliteapp.bean.SeminarBean;
import com.op.teachingliteapp.common.Common;
import com.op.teachingliteapp.common.api.teachinglite.SeminarsUrl;
import com.op.teachingliteapp.database.dao.SeminarDao;
import com.op.teachingliteapp.fragment.courseDiscussion.sonCourseDiscussion.sonSeminarFragment;
import com.op.teachingliteapp.util.ScreenSendUtils;
import com.op.teachingliteapp.util.SharedPreferenceUtil;
import com.op.teachingliteapp.util.StringUtils;
import com.op.teachingliteapp.util.asynctask.HttpPostTask;
import com.op.teachingliteapp.util.asynctask.OnTaskProcessListener;

/*
 * 课程讨论
 * 2015.7.11 by kim zhang
 */
public class SeminarFragment extends Fragment {

	private static final String TAG = SeminarFragment.class.getSimpleName();
	private View root;
	private SeminarAdapter madapter;
	private String getCourseUserId, getCourseId;
	ArrayList<SeminarData> discussion_List = new ArrayList<SeminarData>();

	// private ListView listView;
	// private JSONObject jsonobjectresult;
	// private String message;
	// private JSONObject resultMap;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		final View root = inflater.inflate(R.layout.fragment_course_discussion, container, false);
		this.root = root;

		SharedPreferences preferences = getActivity().getSharedPreferences("TeachingLite", Context.MODE_PRIVATE);
		getCourseUserId = preferences.getString(Common.Prefs.USER_ID, "");
		getCourseId = preferences.getString(Common.Prefs.COURSE_ID, "");
		downLoadData();
		ListView listView = (ListView) root.findViewById(R.id.Discussion);
		Log.i("SeminarFragment", getCourseId+"");
		madapter = new SeminarAdapter(getActivity(), discussion_List);
		listView.setAdapter(madapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
				Map<String, Object> prefsMap = new HashMap<String, Object>();
				prefsMap.put(Common.Prefs.SEMINAR_ID, madapter.getSeminarId(position));
				SharedPreferenceUtil.saveData(getActivity(), prefsMap);
				getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.main_show2, new sonSeminarFragment()).commit();
				
			}
		});

		listView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == SCROLL_STATE_IDLE) {
					Log.i(TAG, "SCROLL_STATE_IDLE");
					ScreenSendUtils.sendWithDely(root);

				}

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

			}
		});

		return root;
	}

	@Override
	public void onResume() {
		super.onResume();
		// ScreenSendUtils.send(root);
	}

	/**
	 * 通过courseId从网上下拉主贴json
	 */
	public void downLoadData() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("courseId", getCourseId));
		HttpPostTask task = new HttpPostTask(getActivity(), SeminarsUrl.GET_ROOT_SEMINARS_BY_COURSE_ID, params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
			}

			@Override
			public void completed(String result) {
				if (StringUtils.isEmptyOrStringNull(result)) {
					getDataFromDatabase();
				} else {
					Log.i(TAG, "解析" + result);
					// 有网络登陆时
					analyticalSeminar(result);
					getDataFromDatabase();
				}
				madapter.notifyDataSetChanged();
				// 这是用来传屏的。数据更新完就调这句话
				ScreenSendUtils.sendWithDely(root);

			}

		});
		task.execute();// 执行结束，圈转完

	}

	/**
	 * 从数据库获取数据 // 从数据库提取课程讨论主贴内容
	 */
	public void getDataFromDatabase() {
		SeminarDao seminarDao = new SeminarDao(getActivity(), getCourseUserId);
		List<SeminarBean> seminar = seminarDao.getSeminarByCourseId(getCourseId);
		discussion_List.clear();
		// 获取讨论标题
		for (int i = 0; i < seminar.size(); i++) {
			String title = seminar.get(i).getTitle();
			String time = seminar.get(i).getCreateTime();
			String context = seminar.get(i).getContent();
			String name = seminar.get(i).getUserBean().getName();
			String avatar = seminar.get(i).getUserBean().getImageUrl();
			String like = seminar.get(i).getLikeCount();// 点赞
			String ChildCount = seminar.get(i).getChildCount();// 评论数
			String image = seminar.get(i).getImageUrl();
			String userid = seminar.get(i).getUserBean().getId();
			String seminarId = seminar.get(i).getId();
			String seminarParentId = seminar.get(i).getParentId();
			Log.i(TAG, "userId " + userid);
			Log.i(TAG, "头像 " + avatar);
			Log.i(TAG, "点赞数 " + like);
			Log.i(TAG, "评论数" + ChildCount);
			Log.i(TAG, "图片" + image);
			Log.i(TAG, "seminarParentId*******************" + seminarParentId);
			/*
			 * 依次是名字，头像,时间，点赞，评论次数,标题,内容,图片,用户id,seminarId
			 */
			discussion_List.add(new SeminarData(name, avatar, time, like, ChildCount, title, context, image, userid, seminarId));
		}
	}

	/**
	 * 解析主贴或子贴json，并存入数据库
	 * 
	 * @param result
	 * 
	 */
	public void analyticalSeminar(String result) {

		// 判断得到的数据是否为null
		if (!StringUtils.isEmptyOrStringNull(result)) {
			try {
				JSONObject jsonobjectresult = new JSONObject(result);
				String message = jsonobjectresult.getString("message");
				// 不存在parent，即主贴时
				if (message.equals("Success")) {
					SeminarDao seminarDao = new SeminarDao(getActivity(), getCourseUserId);
					// 清空数据库
					seminarDao.empty();
					JSONObject resultMap = jsonobjectresult.getJSONObject("resultMap");
					JSONArray seminarList = resultMap.getJSONArray("seminarList");
					for (int i = 0; i < seminarList.length(); i++) {
						JSONObject seminar = new JSONObject();
						seminar = seminarList.getJSONObject(i);

						// 将JsonObject存入本地数据库
						SeminarBean seminarBean = new SeminarBean();
						seminarBean.fillAttributeByJson(seminar);
						seminarDao.insertOrUpdate(seminarBean);
					}

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

}
